package com.zbkj.service.service.order.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.zbkj.common.enums.ProductTypeEnum;
import com.zbkj.common.exception.CommonException;
import com.zbkj.common.model.order.OrderDetail;
import com.zbkj.common.model.product.Product;
import com.zbkj.common.model.user.User;
import com.zbkj.common.request.order.ClientOrderSaveRequest;
import com.zbkj.common.request.order.OrderDetailSaveRequest;
import com.zbkj.common.response.order.OrderDetailResponse;
import com.zbkj.service.dao.order.OrderDetailMapper;
import com.zbkj.service.service.order.OrderDetailService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单明细表 服务实现类
 * </p>
 *
 * @author 
 * @since 2024-09-15
 */
@Service
public class OrderDetailServiceImpl extends ServiceImpl<OrderDetailMapper, OrderDetail> implements OrderDetailService {

    @Resource
    private OrderDetailMapper orderDetailMapper;

    @Override
    public List<OrderDetail> getListByOrderIds(List<Long> orderIdList) {
        if(CollectionUtils.isEmpty(orderIdList)) {
            return Lists.newArrayList();
        }
        LambdaQueryWrapper<OrderDetail> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderDetail::getDeleteFlag,0)
                .in(OrderDetail::getOrderId,orderIdList);
        return this.list(wrapper);
    }

    @Override
    public Map<Long, List<OrderDetail>> getGroupOrderIdMap(List<Long> orderIdList) {
        List<OrderDetail> detailList = getListByOrderIds(orderIdList);
        return detailList.stream().collect(Collectors.groupingBy(v->v.getOrderId()));
    }

    @Override
    public List<OrderDetailResponse> pojoToDetailResp(List<OrderDetail> detailList) {
        List<OrderDetailResponse> responseList = Lists.newArrayList();
        for(OrderDetail detail : detailList) {
            OrderDetailResponse resp = new OrderDetailResponse();
            BeanUtils.copyProperties(detail,resp);
            responseList.add(resp);
        }
        return responseList;
    }

    @Override
    public List<OrderDetail> saveOrderParamCheckAndPojoBuild(List<OrderDetailSaveRequest> detailReqList, User user, List<Product> dbProductList, Date currentDate) {
        if(CollectionUtils.isEmpty(dbProductList)) {
            throw new CommonException("商品信息不存在,请刷新后重试");
        }
        List<OrderDetail> orderDetails = Lists.newArrayList();
        Map<Long, Product> dbProductMap = dbProductList.stream().collect(Collectors.toMap(k->k.getId(),v->v,(ov,nv)->nv));
        int yearCarNum=0;
        for(OrderDetailSaveRequest detailReq : detailReqList) {
            Product product = dbProductMap.getOrDefault(detailReq.getProductId(),null);
            if(Objects.isNull(product)) {
                throw new CommonException("购买商品已下架，请刷新后重试");
            }
            if(ProductTypeEnum.isType1(product.getProductType())) {
                yearCarNum += detailReq.getProductNum();
            } else if(ProductTypeEnum.isType2(product.getProductType())) {
            } else {
                throw new CommonException("商品类型错误");
            }
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setProductId(product.getId());
            orderDetail.setProductName(product.getProductName());
            orderDetail.setProductType(product.getProductType());
            orderDetail.setProductPrice(product.getProductPrice());
            orderDetail.setDataval(product.getProductDataval());
            orderDetail.setProductNum(detailReq.getProductNum());
            orderDetail.setTotalPrice(product.getProductPrice().multiply(BigDecimal.valueOf(detailReq.getProductNum())));
            orderDetail.setTotalDataval(product.getProductDataval() * detailReq.getProductNum());
            orderDetails.add(orderDetail);
        }
//        if(yearCarNum>1) {
//            throw new CommonException("年卡只能购买1份");
//        } else if(yearCarNum == 1) {
//            if((Objects.nonNull(user.getCardExpire()) && user.getCardExpire().getTime()>=currentDate.getTime())) {
//                throw new CommonException("当前持有年卡未失效，不能在购买年卡");
//            } else {
//                int cardOrderNum = this.getValidYearProductOrderCount(user.getId());
//                if(cardOrderNum>0) {
//                    throw new CommonException("存在处理中的购买年卡订单，不能在购买年卡");
//                }
//            }
//        } else {
//            if(Objects.isNull(user.getCardExpire()) || user.getCardExpire().getTime()<currentDate.getTime()) {
//                throw new CommonException("请先开通年卡");
//            }
//        }
        return orderDetails;
    }

    @Override
    public List<OrderDetail> reportOrderParamCheckAndPojoBuild(List<OrderDetailSaveRequest> detailReqList, List<Product> dbProductList) {
        if(CollectionUtils.isEmpty(dbProductList)) {
            throw new CommonException("报告包商品不存在,请刷新后重试");
        }
        List<OrderDetail> orderDetails = Lists.newArrayList();
        Map<Long, Product> dbProductMap = dbProductList.stream().collect(Collectors.toMap(k->k.getId(),v->v,(ov,nv)->nv));
        for(OrderDetailSaveRequest detailReq : detailReqList) {
            Product product = dbProductMap.getOrDefault(detailReq.getProductId(),null);
            if(Objects.isNull(product)) {
                throw new CommonException("报告包商品已下架，请刷新后重试");
            }
            if(!ProductTypeEnum.isType3(product.getProductType())) {
                throw new CommonException("商品类型错误");
            }
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setProductId(product.getId());
            orderDetail.setProductName(product.getProductName());
            orderDetail.setProductType(product.getProductType());
            orderDetail.setProductPrice(product.getProductPrice());
            orderDetail.setDataval(product.getProductDataval());
            orderDetail.setProductNum(detailReq.getProductNum());
            orderDetail.setTotalPrice(product.getProductPrice().multiply(BigDecimal.valueOf(detailReq.getProductNum())));
            orderDetail.setTotalDataval(product.getProductDataval() * detailReq.getProductNum());
            orderDetails.add(orderDetail);
        }
        return orderDetails;
    }

    @Override
    public int getValidYearProductOrderCount(Long userId) {
        if(Objects.isNull(userId)) {
            return 0;
        }
        return orderDetailMapper.getValidYearProductOrderCount(userId);
    }

    @Override
    public BigDecimal calcTotalDetailFromDetail(List<OrderDetail> orderDetailList) {
        BigDecimal calcAmout = BigDecimal.ZERO;
        for(OrderDetail orderDetail : orderDetailList) {
            calcAmout = calcAmout.add(orderDetail.getTotalPrice());
        }
        return calcAmout;
    }

    @Override
    public OrderDetail orderDetailBuild(Product product, long productNum) {
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setProductId(product.getId());
        orderDetail.setProductName(product.getProductName());
        orderDetail.setProductType(product.getProductType());
        orderDetail.setProductPrice(product.getProductPrice());
        orderDetail.setDataval(product.getProductDataval());
        orderDetail.setProductNum(productNum);
        orderDetail.setTotalPrice(product.getProductPrice().multiply(BigDecimal.valueOf(productNum)));
        orderDetail.setTotalDataval(product.getProductDataval() * productNum);
        return orderDetail;
    }
}
